package com.klikmee.sms.chat.web.filters;

import java.text.MessageFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;

import com.klikmee.sms.cef.CoreAdapter;
import com.klikmee.sms.cef.services.Service;
import com.klikmee.sms.chat.web.dao.AnswerDAO;
import com.klikmee.sms.chat.web.dao.ChatMemberDao;
import com.klikmee.sms.chat.web.dao.QuestionDAO;
import com.klikmee.sms.services.chat.model.Answer;
import com.klikmee.sms.services.chat.model.ChatMember;
import com.klikmee.sms.services.chat.model.Question;

/**
 * Subscribes customer to list of available people for chat. After subscription
 * list of available poeople aliases is sent back to the subscriber.
 * 
 * @author makcro
 * 
 */
public class SubscriptionFilter implements MessageFilter {

	/**
	 * Core id of the subscription service
	 */
	private Long subsciptionServiceId;
	
	/**
	 * charging for the subscription message response
	 */
	private Long chargingId;
	/**
	 * Logger instance
	 */
	private Logger logger = Logger.getLogger(SubscriptionFilter.class);
	

	/**
	 * Instance of core adapter used to send 
	 */
	private CoreAdapter coreAdapter;
	/**
	 * Reference to the {@link ChatMember} DAO service
	 */
	private ChatMemberDao chatMemberDao = null;

	/**
	 * Ref to the answer dao
	 */
	private AnswerDAO answerDAO = null;
	/**
	 * Keyword that activates this listener. Listener matches message text in
	 * search for keyword
	 * 
	 */
	
	private QuestionDAO questionDAO = null;
	
	/**
	 * Regular expression which if matched activates this listener.
	 */
	private String activationExpression = null;

	private String messageTemplate = null;

	/**
	 * number of chat members to return to subscriber
	 */
	private int answerListSize;

	

	/**
	 * Subscribes customer to members list.
	 * Activates on request text and keyword successful match.
	 * 
	 * @return true if customer is subscribed, false otherwise
	 */
	@Override
	public boolean processMessage(Question question) {

		// test if question matches keyword expression
		if (question.getQuestion().matches(activationExpression)) {
			
			logger.info(MessageFormat.format("Successful activatoin match on subscription filter message id = [{0}]", question.getCoreID()));
			
			String messageText = createMessageBody();

			Long coreId = this.coreAdapter.sendMessage(chargingId, subsciptionServiceId, Service.SERVICE_FLAG_SEMANTIC_OK, question.getCoreID(), messageText);

			// create answer object
			Answer answer = new Answer();
			answer.setCoreID(coreId);
			answer.setAnswer(messageText);
			answer.setDateAnswered(new Date());
			answer.setFromNumber(question.getToNumber());
			answer.setToNumber(question.getFromNumber());
			answer.setVisable(false);
			answer.setQuestion(question);
			
			answerDAO.create(answer);
			
			// update question so it's not visible to operaters
			question.setVisable(false);
			questionDAO.edit(question);
			
			return true;
		}

		return false;
	}

	private String createMessageBody() {
		// load all members from database
		List<String> allMembersAliases = chatMemberDao.findAllMembersAliases();
		// shuffle list
		Collections.shuffle(allMembersAliases);
		// randomize number of names returned limited by answer list size
		Random random = new Random();
		int listSize = random.nextInt(getAnswerListSize()) + 1;
		int limit = listSize > allMembersAliases.size() ? allMembersAliases.size() : listSize;
		
		List<String> truncated = allMembersAliases.subList(0, limit);

		String memberAliases = org.apache.commons.lang.StringUtils.join(truncated, ',');

		String messageText = MessageFormat.format(getMessageTemplate(), memberAliases);
		return messageText;
	}

	public void setChatMemberDao(ChatMemberDao chatMemberDao) {
		this.chatMemberDao = chatMemberDao;
	}

	public void setActivationExpression(String activationExpression) {
		this.activationExpression = activationExpression;
	}

	public void setMessageTemplate(String messageTemplate) {
		this.messageTemplate = messageTemplate;
	}

	public void setAnswerDAO(AnswerDAO answerDAO) {
		this.answerDAO = answerDAO;
	}
	public void setAnswerListSize(int answerListSize) {
		this.answerListSize = answerListSize;
	}
	
	public void setQuestionDAO(QuestionDAO questionDAO) {
		this.questionDAO = questionDAO;
	}
	
	public String getMessageTemplate() {
		return messageTemplate;
	}
	
	
	public int getAnswerListSize() {
		return answerListSize;
	}
	
	public void setCoreAdapter(CoreAdapter coreAdapter) {
		this.coreAdapter = coreAdapter;
	}

	public void setSubsciptionServiceId(Long subsciptionServiceId) {
		this.subsciptionServiceId = subsciptionServiceId;
	}

	public void setChargingId(Long chargingId) {
		this.chargingId = chargingId;
	}

	
}
